﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Text;
using MM.DBUtility;

namespace MobileManager
{
    public partial class MchannelManage : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["CurUser"] == null)
                {
                    Response.Redirect("Login.aspx");
                    return;
                }
                else
                {
                    userModel = (MM.Model.T_Users)Session["CurUser"];
                }
                if (!IsPostBack)
                {
                    BindSPbusi(ref ddlSP);
                    ddlSP.Items.Insert(0, new ListItem("全部", "-1"));

                    BindDdlODEP(ref ddlOP);
                    ddlOP.Items.Insert(0, new ListItem("全部", "-1"));

                    GVDataBindAll();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void BindDdlODEP(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ONO,ONO+'-'+ OName as Name FROM T_ODEP WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "ONO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindSPbusi(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT SNO,SPName FROM T_SPbusi WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "SNO";
            ddl.DataTextField = "SPName";
            ddl.DataBind();
        }

        protected void btnADD_Click(object sender, EventArgs e)
        {
            try
            {
                string strNO = txtAddNO.Text.Trim();
                if (string.IsNullOrEmpty(strNO))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道编号不能为空！");
                    return;
                }
                string strNumber = txtAddNumber.Text.Trim();
                if (string.IsNullOrEmpty(strNumber))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道号码不能为空！");
                    return;
                }
                string strOrder = txtAddOrder.Text;
                if (string.IsNullOrEmpty(strOrder))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道指令不能为空！");
                    return;
                }
                string strChannelPrice = txtAddPirce.Text.Trim();
                if (string.IsNullOrEmpty(strChannelPrice))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道价格不能为空！");
                    return;
                }
                string strChannelPriceRate = txtAddPirceRate.Text.Trim();
                if (string.IsNullOrEmpty(strChannelPriceRate))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "分成比例不能为空！");
                    return;
                }

                string strProIDs = string.Empty;
                for (int i = 0; i < cblProvince.Items.Count; i++)
                {
                    if (cblProvince.Items[i].Selected)
                        strProIDs += cblProvince.Items[i].Value + ";";
                }

                ArrayList alSQL = new ArrayList();
                if (!txtAddNO.Enabled)
                {
                    alSQL.Add(string.Format("DELETE FROM T_Channel WHERE ChannelNO='{0}'", strNO));
                    alSQL.Add(string.Format("DELETE FROM T_Mask WHERE ChannelNO='{0}'", strNO));
                    //alSQL.Add(string.Format("DELETE FROM T_Double WHERE ChannelNO='{0}'", strNO));
                }
                else
                {
                    if (BLSqlData.ExistChannelNO(strNO))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "通道编号已经存在，请更换！");
                        return;
                    }
                }

                alSQL.Add(string.Format("INSERT INTO T_Channel(ChannelNO,ChannelNumber,ChannelOrder,ChannelPrice,SNO,ChannelPro,ONO,ChannelPriceReal,LimitTime,Mark,Flag) VALUES('{0}','{1}','{2}',{3},'{4}','{5}','{6}',{7},{8},N'{9}','1')", strNO, strNumber, strOrder, strChannelPrice, ddlSPbusi.SelectedValue, strProIDs, ddlODEP.SelectedValue, strChannelPriceRate, ddlLimitTime.SelectedValue, txtMark.Text.Trim()));

                //屏蔽信息
                for (int i = 0; i < cblChinase.Items.Count; i++)
                {
                    if (cblChinase.Items[i].Selected)
                        alSQL.Add(string.Format("INSERT INTO T_Mask(ChannelNO,Chinese) VALUES('{0}',N'{1}')", strNO, cblChinase.Items[i].Text));
                }

                for (int i = 0; i < cblEnglish.Items.Count; i++)
                {
                    if (cblEnglish.Items[i].Selected)
                        alSQL.Add(string.Format("INSERT INTO T_Mask(ChannelNO,English) VALUES('{0}','{1}')", strNO, cblEnglish.Items[i].Text));
                }

                for (int i = 0; i < cblNumber.Items.Count; i++)
                {
                    if (cblNumber.Items[i].Selected)
                        alSQL.Add(string.Format("INSERT INTO T_Mask(ChannelNO,TelNumber) VALUES('{0}','{1}')", strNO, cblNumber.Items[i].Text));
                }

                MM.DBUtility.DbHelperSql.ExecuteSqlTran(alSQL);
                //if (txtAddNO.Enabled)
                //    MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("添加了通道信息：通道编号={0}。", strNO), "通道管理");
                MM.Common.Common.PageStartAlert(this.Page, "保存成功！");
                divAdd.Visible = false;
                divQuery.Visible = true;
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnQueryAll_Click(object sender, EventArgs e)
        {
            try
            {
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region GV info
        private void GVDataBind()
        {
            string strSQL = "SELECT a.LimitTime,a.ChannelNO,a.ONO,a.ChannelPriceReal,a.ChannelNumber,a.ChannelOrder,a.ChannelPrice,a.ChannelPro,a.Mark,b.SPName FROM T_Channel a WITH(NOLOCK) LEFT JOIN T_SPbusi b on a.SNO=b.SNO WHERE 1=1";
            if (!string.IsNullOrEmpty(txtNO.Text.Trim()))
                strSQL += string.Format(" AND a.ChannelNO LIKE '%{0}%'", txtNO.Text.Trim());
            if (!string.IsNullOrEmpty(txtNumber.Text.Trim()))
                strSQL += string.Format(" AND a.ChannelNumber LIKE '%{0}%'", txtNumber.Text.Trim());
            if (!string.IsNullOrEmpty(txtOrder.Text.Trim()))
                strSQL += string.Format(" AND a.ChannelOrder LIKE '%{0}%'", txtOrder.Text.Trim());

            if (!"-1".Equals(ddlOP.SelectedValue))
                strSQL += string.Format(" AND a.ONO='{0}'", ddlOP.SelectedValue);
            if (!"-1".Equals(ddlSP.SelectedValue))
                strSQL += string.Format(" AND a.SNO='{0}'", ddlSP.SelectedValue);

            strSQL += " ORDER BY a.CreateTime DESC";

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            ViewState["DataTemp"] = ds;
        }
        private void GVDataBindAll()
        {
            string strSQL = "SELECT a.LimitTime,a.ChannelNO,a.ONO,a.ChannelPriceReal,a.ChannelNumber,a.ChannelOrder,a.ChannelPrice,a.ChannelPro,a.Mark,b.SPName FROM T_Channel a WITH(NOLOCK) LEFT JOIN T_SPbusi b on a.SNO=b.SNO ORDER BY a.CreateTime DESC";
            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            ViewState["DataTemp"] = ds;
        }
        protected void GVinfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GVinfo.EditIndex = -1;
                GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
                GVinfo.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
            {
                string strPros = ((HiddenField)e.Row.FindControl("HFPros")).Value;
                string strProNames = string.Empty;
                if (!string.IsNullOrEmpty(strPros))
                {
                    strPros = strPros.Replace(";", ",");
                    strPros = strPros.Remove(strPros.LastIndexOf(","));

                    DataTable dt = DbHelperSql.Query(string.Format("SELECT * FROM T_Province WITH(NOLOCK) WHERE ProvinceID IN ({0})", strPros)).Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            strProNames += row["ProvinceName"].ToString() + "，";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(strProNames))
                    strProNames = strProNames.Remove(strProNames.LastIndexOf("，"));

                Label lbPros = (Label)e.Row.FindControl("lbPros");
                lbPros.Text = strProNames;

                Label lb = (Label)e.Row.FindControl("lbLimitTime");
                string strLimitTime = lb.Text;
                if (strLimitTime.Equals("0"))
                    lb.Text = "无限制";
                else if (strLimitTime.Equals("7"))
                    lb.Text = "0-7";
                else if (strLimitTime.Equals("8"))
                    lb.Text = "0-8";
            }
        }

        protected void GVinfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                string strNO = ((HiddenField)GVinfo.Rows[e.RowIndex].FindControl("HF2")).Value;
                ArrayList alist = new ArrayList();
                alist.Add(string.Format("DELETE FROM T_Channel WHERE ChannelNO='{0}'", strNO));
                alist.Add(string.Format("DELETE FROM T_Rules WHERE ChannelNO='{0}'", strNO));
                alist.Add(string.Format("DELETE FROM T_Mask WHERE ChannelNO='{0}'", strNO));
                alist.Add(string.Format("DELETE FROM T_MaskArea WHERE ChannelNO='{0}'", strNO));
                DbHelperSql.ExecuteSqlTran(alist);

                //MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("删除了通道信息：通道编号={0}，同时删除了相应规则信息。", strNO), "通道管理");
                MM.Common.Common.PageStartAlert(this.Page, "删除成功！");
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                divQuery.Visible = false;
                divAdd.Visible = true;

                string strNO = ((Label)GVinfo.Rows[e.NewEditIndex].FindControl("lbNO")).Text.Trim();
                DataTable dt = DbHelperSql.Query(string.Format("SELECT * FROM T_Channel WITH(NOLOCK) WHERE ChannelNO='{0}'", strNO)).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    BindDdlODEP(ref ddlODEP);
                    BindSPbusi(ref ddlSPbusi);
                    ddlLimitTime.SelectedValue = dt.Rows[0]["LimitTime"].ToString();
                    ddlSPbusi.SelectedValue = dt.Rows[0]["SNO"].ToString();
                    ddlODEP.SelectedValue = dt.Rows[0]["ONO"].ToString();
                    txtAddNO.Text = strNO;
                    txtAddNO.Enabled = false;
                    txtAddNumber.Text = dt.Rows[0]["ChannelNumber"].ToString();
                    txtAddOrder.Text = dt.Rows[0]["ChannelOrder"].ToString();
                    txtAddPirce.Text = dt.Rows[0]["ChannelPrice"].ToString();
                    txtAddPirceRate.Text = dt.Rows[0]["ChannelPriceReal"].ToString();
                    if (dt.Rows[0]["Mark"] != null)
                        txtMark.Text = dt.Rows[0]["Mark"].ToString();
                    else txtMark.Text = "";

                    BindProvice();
                    string strPros = ";" + dt.Rows[0]["ChannelPro"].ToString();
                    for (int i = 0; i < cblProvince.Items.Count; i++)
                    {
                        if (strPros.Contains(";" + cblProvince.Items[i].Value + ";"))
                            cblProvince.Items[i].Selected = true;
                    }

                    BindMaskChina();
                    for (int i = 0; i < cblChinase.Items.Count; i++)
                    {
                        if (CheckValue("Chinase", strNO, cblChinase.Items[i].Text.Trim(), "T_Mask"))
                            cblChinase.Items[i].Selected = true;
                    }

                    BindMaskEnglish();
                    for (int i = 0; i < cblEnglish.Items.Count; i++)
                    {
                        if (CheckValue("English", strNO, cblEnglish.Items[i].Text.Trim(), "T_Mask"))
                            cblEnglish.Items[i].Selected = true;
                    }

                    BindMaskNumber();
                    for (int i = 0; i < cblNumber.Items.Count; i++)
                    {
                        if (CheckValue("Number", strNO, cblNumber.Items[i].Text.Trim(), "T_Mask"))
                            cblNumber.Items[i].Selected = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private bool CheckValue(string Flag, string strNO, string strValue, string strTable)
        {
            if (Flag.Equals("Chinase"))
            {
                return DbHelperSql.Exists(string.Format("SELECT COUNT(*) FROM {2} WITH(NOLOCK) WHERE ChannelNO='{0}' AND Chinese=N'{1}'", strNO, strValue, strTable));
            }
            else if (Flag.Equals("English"))
            {
                return DbHelperSql.Exists(string.Format("SELECT COUNT(*) FROM {2} WITH(NOLOCK) WHERE ChannelNO='{0}' AND English='{1}'", strNO, strValue, strTable));
            }
            else if (Flag.Equals("Number"))
            {
                return DbHelperSql.Exists(string.Format("SELECT COUNT(*) FROM {2} WITH(NOLOCK) WHERE ChannelNO='{0}' AND TelNumber='{1}'", strNO, strValue, strTable));
            }
            else return false;
        }

        protected void GVinfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                string strNO = ((HiddenField)GVinfo.Rows[e.RowIndex].FindControl("HF1")).Value;

                string strNumber = ((TextBox)GVinfo.Rows[e.RowIndex].FindControl("txtNumber")).Text.Trim();
                if (string.IsNullOrEmpty(strNumber))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道号码不能为空！");
                    return;
                }
                string strOrder = ((TextBox)GVinfo.Rows[e.RowIndex].FindControl("txtOrder")).Text;
                if (string.IsNullOrEmpty(strOrder))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道指令不能为空！");
                    return;
                }
                string strPrice = ((TextBox)GVinfo.Rows[e.RowIndex].FindControl("txtPrice")).Text.Trim();
                if (string.IsNullOrEmpty(strPrice))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "通道价格不能为空！");
                    return;
                }
                string strPriceRate = ((TextBox)GVinfo.Rows[e.RowIndex].FindControl("txtPriceRate")).Text.Trim();
                if (string.IsNullOrEmpty(strPriceRate))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "分成比例不能为空！");
                    return;
                }

                MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Channel SET ChannelNumber='{0}',ChannelOrder='{1}',ChannelPrice='{2}',ChannelRate={3} WHERE ChannelNO='{4}'", strNumber, strOrder, strPrice, strPriceRate, strNO));
                //MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("更新了通道信息：通道编号={0}。", strNO), "通道管理");
                MM.Common.Common.PageStartAlert(this.Page, "更新成功！");

                GVinfo.EditIndex = -1;
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GVinfo.PageIndex = e.NewPageIndex;
            GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
            GVinfo.DataBind();
        }
        #endregion

        protected void btnADDNew_Click(object sender, EventArgs e)
        {
            divAdd.Visible = true;
            divQuery.Visible = false;

            txtAddNO.Enabled = true;
            txtAddNO.Text = "";
            txtAddNumber.Text = "";
            txtAddOrder.Text = "";
            txtAddPirce.Text = "";

            BindSPbusi(ref ddlSPbusi);
            BindDdlODEP(ref ddlODEP);
            BindProvice();
            BindMaskChina();
            BindMaskEnglish();
            BindMaskNumber();
        }
        private void BindProvice()
        {
            cblProvince.Items.Clear();
            cblProvince.DataSource = MM.DBUtility.BLSqlData.AllProvince;
            cblProvince.DataValueField = "ProvinceID";
            cblProvince.DataTextField = "ProvinceName";
            cblProvince.DataBind();
        }
        private void BindMaskChina()
        {
            cblChinase.Items.Clear();
            cblChinase.DataSource = DbHelperSql.Query("SELECT * FROM T_MaskChina WITH(NOLOCK)").Tables[0];
            cblChinase.DataTextField = "TextValue";
            cblChinase.DataValueField = "ID";
            cblChinase.DataBind();
        }
        private void BindMaskEnglish()
        {
            cblEnglish.Items.Clear();
            cblEnglish.DataSource = DbHelperSql.Query("SELECT * FROM T_MaskEnglish WITH(NOLOCK)").Tables[0];
            cblEnglish.DataTextField = "TextValue";
            cblEnglish.DataValueField = "ID";
            cblEnglish.DataBind();
        }
        private void BindMaskNumber()
        {
            cblNumber.Items.Clear();
            cblNumber.DataSource = DbHelperSql.Query("SELECT * FROM T_MaskNumber WITH(NOLOCK)").Tables[0];
            cblNumber.DataTextField = "TextValue";
            cblNumber.DataValueField = "ID";
            cblNumber.DataBind();
        }
        protected void btnBack_Click(object sender, EventArgs e)
        {
            divAdd.Visible = false;
            divQuery.Visible = true;
        }
    }
}
